using AutoMapper;
using MediatR;
using S.O.Api.Write.Application.Command.Permission;
using S.O.Domain.RBAC;
using S.O.ErrorCode;
using S.O.Interstructrue.Base;

namespace S.O.Api.Write.Application.Handler.Permission
{
    /// <summary>
    /// 创建权限处理器
    /// 负责处理权限创建的业务逻辑
    /// </summary>
    public class CreatePermissionHandler : IRequestHandler<CreatePermissionCommand, APIResult<int>>
    {
        /// <summary>
        /// 权限仓储接口，用于权限数据的CRUD操作
        /// </summary>
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        
        /// <summary>
        /// 对象映射器，用于Command对象到Model对象的转换
        /// </summary>
        private readonly IMapper mapper;
        
        /// <summary>
        /// 日志记录器，用于记录操作日志和错误信息
        /// </summary>
        private readonly ILogger<CreatePermissionHandler> logger;

        /// <summary>
        /// 构造函数，通过依赖注入初始化所需的服务
        /// </summary>
        /// <param name="permissionRepository">权限仓储服务</param>
        /// <param name="mapper">对象映射服务</param>
        /// <param name="logger">日志记录服务</param>
        public CreatePermissionHandler(IBaseRepository<PermissionModel> permissionRepository, IMapper mapper, ILogger<CreatePermissionHandler> logger)
        {
            this.permissionRepository = permissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        /// <summary>
        /// 处理创建权限命令
        /// 执行权限创建操作
        /// </summary>
        /// <param name="request">创建权限命令对象，包含要创建的权限信息</param>
        /// <param name="cancellationToken">取消令牌，用于取消异步操作</param>
        /// <returns>返回包含操作结果的APIResult对象</returns>
        public Task<APIResult<int>> Handle(CreatePermissionCommand request, CancellationToken cancellationToken)
        {
            // 初始化返回结果对象
            APIResult<int> res = new APIResult<int>();
            
            // 使用AutoMapper将请求对象映射为权限实体对象
            var permission = mapper.Map<PermissionModel>(request);
            
            // 执行权限创建操作
            var r = permissionRepository.Create(permission);
            
            // 根据创建结果返回相应的响应
            if(r > 0)
            {
                res.Data = r;
                res.Code = APIEnums.Success;
                res.Msg = "添加成功";
                logger.LogInformation($"创建权限成功，权限名称：{permission.PermissionName}");
                return Task.FromResult(res);
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "创建失败";
                res.Data = r;
                logger.LogError($"创建权限失败，权限名称：{permission.PermissionName}");
                return Task.FromResult(res);
            }
        }
    }
}
